package com.mwm.loyal.util;

import com.mwm.loyal.bean.ContactBean;
import com.mwm.loyal.bean.ResultMap;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.*;

public class DataUtil {
    private static final String className = "oracle.jdbc.driver.OracleDriver";
    private static final String user = "loyal";
    private static final String password = "111111";
    private static final ResultMap resultMap = ResultMap.getInstance();

    public static void doDownLoadApk(HttpServletResponse response) {
        File copyFile = new File("E:\\Oracle\\apks\\mwm.apk");
        File file = new File("E:\\Oracle\\apks\\mwm.apk");
        if (!copyFile.exists()) {
            new CopyFileThread(file, copyFile).run();
        }
        try (FileInputStream fis = new FileInputStream(copyFile.exists() ? copyFile : file);
             OutputStream outputStream = response.getOutputStream();
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            int length;
            byte[] bytes = new byte[1024];
            while ((length = fis.read(bytes)) != -1) {
                baos.write(bytes, 0, length);
            }
            // byte[] data = new byte[(int) fis.getChannel().size()];
            //fis.read(data);
            byte[] data = baos.toByteArray();
            outputStream.write(data, 0, data.length);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ResultMap doInsertContact(ContactBean contactBean) {
        try (Connection conn = getConnection();
             PreparedStatement pre = conn.prepareStatement("INSERT INTO MWM_CONTACT VALUES (?,?,?)")) {
            pre.setTimestamp(1, TimeUtil.date2Timestamp(contactBean.getTime()));
            pre.setString(2, contactBean.getAccount());
            String contact = contactBean.getContact();
            if (contact.contains("&key="))
                contact = contact.substring(contact.indexOf("&key=")).replace("&key=", "");
            pre.setString(3, contact.contains("&key=") ? contact : contact);
            int result = pre.executeUpdate();
            return resultMap.set(String.valueOf(result), result == -1 ? "用户已存在" : "");
        } catch (Exception e) {
            e.printStackTrace();
            return errorBean(e);
        }
    }

    public static ResultMap doUpdateIcon(String account, InputStream inputStream) {
        try (Connection conn = getConnection();
             PreparedStatement pre = conn.prepareStatement("UPDATE  MWM_USER SET ICON= ? WHERE ACCOUNT= ?")) {
            pre.setBlob(1, inputStream);
            pre.setString(2, account);
            int result = pre.executeUpdate();
            resultMap.setCode(String.valueOf(result));
            if (result == 0)
                resultMap.setMessage("用户不存在，请注册");
            else if (result == -1)
                resultMap.setMessage("更新失败");
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return errorBean(e);
        }
    }

    public static ResultMap doUpdateApk(String apkName, String version, InputStream inputStream) {
        Connection conn = null;
        PreparedStatement pre = null;
        ResultSet resultSet = null;
        try {
            conn = getConnection();
            pre = conn.prepareStatement("SELECT * FROM MWM_UPDATE");
            resultSet = pre.executeQuery();
            while (resultSet.next()) {
                int result = deleteApk(resultSet.getString("version"));
                if (result != 1)
                    break;
            }
            pre = conn.prepareStatement("INSERT INTO MWM_UPDATE VALUES (?,?,?,?,?)");
            pre.setString(1, apkName);
            pre.setString(2, version);
            pre.setBlob(3, inputStream);
            pre.setTimestamp(4, TimeUtil.getTimestamp());
            pre.setString(5, "1");
            int result = pre.executeUpdate();
            return resultMap.set(String.valueOf(result), result == 1 ? "上传成功" : "上传失败");
        } catch (Exception e) {
            e.printStackTrace();
            return errorBean(e);
        } finally {
            StreamUtil.close(resultSet, conn, pre);
        }
    }

    private static int deleteApk(String appVer) {
        try (Connection conn = getConnection();
             PreparedStatement pre = conn.prepareStatement("DELETE FROM MWM_UPDATE WHERE version =?")) {
            pre.setString(1, appVer);
            return pre.executeUpdate();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    private static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName(className);
        String url = "jdbc:oracle:thin:@" + PubUtils.getLocalHostIpAddress() + ":1521/orcl";
        return DriverManager.getConnection(url, user, password);
    }

    private static void copyFile(File file, File copyFile) {
        byte[] bytes = new byte[1024];
        try (FileInputStream fis = new FileInputStream(file);
             FileOutputStream fos = new FileOutputStream(copyFile);) {
            int length;
            while ((length = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, length);
            }
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static ResultMap errorBean(Exception e) {
        return resultMap.set("-1", e.getMessage());
    }

    private static class CopyFileThread implements Runnable {
        private File file, copyFile;

        CopyFileThread(File file, File copyFile) {
            this.file = file;
            this.copyFile = copyFile;
        }

        @Override
        public void run() {
            copyFile(file, copyFile);
        }
    }
}